package es.unex.meigas.gvsig.core;

import java.util.ArrayList;

import com.hardcode.gdbms.engine.values.Value;
import com.iver.cit.gvsig.fmap.core.IGeometry;
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
import com.iver.cit.gvsig.fmap.layers.FBitSet;
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
import com.vividsolutions.jts.geom.Geometry;

import es.unex.meigas.dataObjects.FeatureImpl;
import es.unex.meigas.dataObjects.IFeature;
import es.unex.meigas.dataObjects.IFeatureIterator;
import es.unex.meigas.exceptions.IteratorException;

public class gvFeatureIterator implements IFeatureIterator {

    private int m_iIndex, m_iSelectedIndex;
    private FBitSet m_BitSet;
    private int m_iCardinality;
    private ReadableVectorial m_RV;
	private ArrayList m_Filters;

    public gvFeatureIterator(FLyrVect layer, ArrayList filters){

        m_iIndex = 0;
        m_iSelectedIndex = 0;
        m_RV = layer.getSource();
        m_BitSet = m_RV.getRecordset().getSelection();
        m_Filters = filters;

        m_iCardinality = m_BitSet.cardinality();

    }

    public boolean hasNext() {

        if (m_iCardinality != 0){
        	return m_iCardinality > m_iSelectedIndex;
        }
        else{
        	try {
				return m_RV.getShapeCount() > m_iSelectedIndex;
			} catch (DriverIOException e) {
				return false;
			}
        }

    }

    public IFeature next() throws IteratorException{

        try{
        	if (m_iCardinality != 0 && m_iCardinality <= m_iSelectedIndex){
        		throw new IteratorException();
        	}
        	if (m_iCardinality != 0){
        		while(!m_BitSet.get(m_iIndex) ){
        			m_iIndex++;
        		}
        	}
        	IGeometry shape = m_RV.getShape(m_iIndex);
        	Geometry geom = shape.toJTSGeometry();
        	Value[] gvSIGValues = m_RV.getRecordset().getRow(m_iIndex);
        	FeatureImpl feature = new FeatureImpl(geom, DataTools.getSextanteValues(gvSIGValues));
        	m_iIndex++;
        	m_iSelectedIndex++;
        	return feature;
        }catch (Exception e){
        	//Sextante.addErrorToLog(e);
        	m_iIndex++;
        	m_iSelectedIndex++;
        	throw new IteratorException();
        }

    }

	public void close() {}

}
